package com.myBlog.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.myBlog.constants.RedisConstants;
import com.myBlog.constants.SystemConstants;
import com.myBlog.domain.entity.Article;
import com.myBlog.mapper.ArticleMapper;
import com.myBlog.utils.RedisCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ViewCountRunner implements CommandLineRunner {

    @Resource
    private ArticleMapper articleMapper;
    @Resource
    private RedisCache redisCache;

    @Override
    public void run(String... args) throws Exception {
        //查询博客信息，id,viewCount
        LambdaQueryWrapper<Article> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_PUBLISH);

        List<Article> articleList = articleMapper.selectList(wrapper);
        Map<String, Integer> viewMap = articleList.stream()
                .collect(Collectors.toMap(article1 -> article1.getId().toString(), article -> {
                            return article.getViewCount().intValue();
                        }
                ));
        //存储到Redis
        redisCache.setCacheMap(RedisConstants.ARTICLE_VIEWCOUNT,viewMap);
    }
}
